package tr.com.netgis;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import tr.com.netgis.log.LogArrayAdapter;
import tr.com.netgis.pojo.NGLocation;
import tr.com.netgis.util.Constants;
import tr.com.netgis.util.Utility;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;

/**
 * First main view of the application, after splash screen
 * @author NetGis
 *
 */
public class MainActivity extends Activity {
	
	private static final String TAG = MainActivity.class
			.getSimpleName();
	
	private ListView logList;
	private TextView logView;
	private Button btnLogViewClear;

	private ArrayList<NGLocation> listItems = new ArrayList<NGLocation>();
	private LogArrayAdapter<NGLocation> adapter;
	private SetLocationApi api;
	private Handler handler;	
	
	final SimpleDateFormat SDF = Utility.createSimpleDateFormat();
	public static String provider;

	private ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG, "Service connection established");

			// that's how we get the client side of the IPC connection
			api = SetLocationApi.Stub.asInterface(service);
			try {
				api.addListener(collectorListener);
			} catch (RemoteException e) {
				Log.e(TAG, "Failed to add listener", e);
			}

			updateLogView();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG, "Service connection closed");
		}
	};

	private SetLocationListener.Stub collectorListener = new SetLocationListener.Stub() {
		@Override
		public void handleLocationsUpdated() throws RemoteException {
			updateLogView();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		handler = new Handler(); // handler will be bound to the current thread
								// (UI)
		logView = (TextView) findViewById(R.id.logView);
		logList = (ListView) findViewById(R.id.logList);
		//WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
		//int height = wm.getDefaultDisplay().getHeight();		
		//logView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,height/2-15));

		btnLogViewClear = (Button) findViewById(R.id.btnLogViewAddTest);
		
		adapter = new LogArrayAdapter<NGLocation>(this, android.R.layout.simple_list_item_1, listItems);
		logList.setAdapter(adapter);
		
		final Context ctx = this;
		
		logList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				NGLocation location =  (NGLocation) arg0.getItemAtPosition(arg2);
				Toast.makeText(ctx, location.toString(), 2).show();
				GeoPoint p = new GeoPoint((int)(location.getLat() * 1e6), (int)(location.getLon() * 1e6));
				_overItem = new OverlayItem(p, "", "");
				showMap();
			}
			
		});
		
		
		btnLogViewClear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				listItems.removeAll(listItems);
				adapter.notifyDataSetChanged();
			}
		});
		

		// start the service explicitly.
		// otherwise it will only run while the IPC connection is up.
		startService(Constants.SET_LOCATION_SERVICE_INTENT);
		bindService(Constants.SET_LOCATION_SERVICE_INTENT, serviceConnection, 0);

		Log.i(TAG, "Activity created");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			api.removeListener(collectorListener);
			unbindService(serviceConnection);
		} catch (Throwable t) {
			Log.w(TAG, "Failed to unbind from the service", t);
		}
		try {
			stopService(Constants.SET_LOCATION_SERVICE_INTENT);			
		} catch (Throwable t) {
			Log.w(TAG, "Failed to stop service", t);
		}
		Log.i(TAG, "Activity destroyed");
		
		Utility.killApp(true);
	}
	
	
	
	private void updateLogView() {
		// doing this in a Handler allows to call this method safely from any
		// thread
		// see Handler docs for more info
		handler.post(new Runnable() {
			@Override
			public void run() {
				try {
					SetLocationResult result = api.getResult();
					Log.i("LOCATION SERVICE", "Handler " + result.getmData());
					// if (result.getTweets().isEmpty()) {
					//if (result.getmData() == null || result.getmData().equals("")) {
					if (result.getLocation() == null) {
						logView.setText("Device ID: " + Utility.getDeviceId() + "\n");
					} else {
						provider = result.getmData();
						Log.d("ARRAYADAPTER: ", result.getLocation().toString());
						listItems.add(result.getLocation());
						adapter.notifyDataSetChanged();		
						FileLogger.log(result.getLocation().toString().trim());
					}
				} catch (Throwable t) {
					Log.e(TAG, "Error while updating the UI with tweets", t);
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = this.getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);

		super.onCreateOptionsMenu(menu);
	    return true;
	}
	
	private void showAbout (){
		Intent intent = new Intent(this, AboutActivity.class);
        startActivity(intent);		
	}

	private void showMessages (){
		Intent intent = new Intent(this, MessagesListActivity.class);
        startActivity(intent);		
	}
	
	private void showSettings(){
		Intent settingsActivity = new Intent(this, Preferences.class);
		startActivity(settingsActivity);	
	}
	
	
	static OverlayItem _overItem;

	private void showMap(){
		Intent mapActivity = new Intent(this, MapViewActivity.class);
		startActivity(mapActivity);			
	}
	
	private void showNotPostedList(){
		Intent act	 = new Intent(this, NotPostedLocationListActivity.class);
		startActivity(act);			
	}
	
	private void showFileLog(){
		Intent fileLogActivity = new Intent(this, FileLogActivity.class);
		startActivity(fileLogActivity);			
	}
	
	/**
	 * Quits all program end stops the background set location service
	 */
	private void quit(){
		this.finish();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.menu_about:
	        showAbout();
	        return true;
	    case R.id.menu_settings:
	        showSettings();
	        return true;
	    case R.id.menu_filelog:
	        showFileLog();
	        return true;
	    case R.id.menu_quit:
	        quit();
	        return true;		        
	    case R.id.menu_notposted:
	    	showNotPostedList();
	    	return true;
	    case R.id.menu_messages:
	    	showMessages();
	    	return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}

	@Override
	protected void onResume() {
		super.onResume();
	}	
	
	
	
}